package com.domain.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.domain.common.Comments;
import com.domain.common.Const;
import com.domain.common.Result;
import com.domain.dao.UsersAlipayMapper;
import com.domain.dao.UsersMapper;
import com.domain.dao.UsersWalletMapper;
import com.domain.pojo.*;
import com.domain.service.BillService;
import com.domain.service.SmsCodeService;
import com.domain.service.UsersWalletService;
import com.domain.utils.ArithmeticUtil;
import com.domain.utils.NotNullUtils;
import com.domain.utils.alipay.AlipayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class UsersWalletServiceImpl implements UsersWalletService {
    @Autowired
    private UsersWalletMapper usersWalletMapper;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private SmsCodeService smsCodeService;


    @Autowired
    private UsersAlipayMapper usersAlipayMapper;

    @Autowired
    private BillService billService;

    /**
     * 我的钱包
     *
     * @param userId
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    public Result getUsersWallet(String userId) {
        Map<String, Object> maps = new HashMap<>();
        UsersWallet usersWa = usersWalletMapper.selectByUserId(userId);
        UsersAlipay alipay = usersAlipayMapper.selectByAlipayUsersId(userId);
        if (usersWa.getBalance().doubleValue() > 0) {
            maps.put("userWallt", usersWa.getBalance().toString());
        } else {
            maps.put("userWallt", "0.00");
        }
        if (NotNullUtils.isNotNullObject(alipay)) {
            maps.put("alipayInfo", alipay);
        } else {
            maps.put("alipayInfo", "");
        }
        return Result.success("操作成功", maps);
    }


    /**
     * 提现
     *
     * @param userId
     * @param money
     * @return
     */
    @Override
    public Result cashWithdrawal(String userId, String smsCode, String money) throws AlipayApiException {
        //验证手机号是否正确
        Users users = usersMapper.selectByPrimaryKey(userId);
        //验证验证码码得时效性（五分钟）
        SmsCode sc = smsCodeService.checkSmsCodeTime(users.getPhone(), smsCode);
        if (!NotNullUtils.isNotNullObject(sc)) {
            return Result.publicResult(Comments.SMSCODE_FAIL, "验证码错误");
        } else {
            Long s = (System.currentTimeMillis() - sc.getCreatTime().getTime()) / (1000 * 60);
            if (s >= 5) {
                //过期删除验证码
                smsCodeService.delect(sc.getId());
                return Result.publicResult(Comments.SMSCODE_CHECK, "验证码已过期！");
            }
        }
        smsCodeService.delect(sc.getId());
        if (Double.parseDouble(money) > 0) {
            //提现到支付宝收取手续费
            //获取支付宝信息
            UsersAlipay usersAlipay = usersAlipayMapper.selectByAlipayUsersId(userId);
            if (NotNullUtils.isNotNullObject(usersAlipay)) {
                //提现费率
                String mul = "0.06";
                BigDecimal moneys = ArithmeticUtil.mul(money, mul);
                BigDecimal mo = ArithmeticUtil.sub(money, moneys.toString());
                AlipayFundTransToaccountTransferResponse r = AlipayUtil.transfer(usersAlipay.getAlipayUserId(), mo.toString());
                if (r.isSuccess()) {
                    //更改用户钱包钱数
                    UsersWallet wa = usersWalletMapper.selectByUserId(userId);
                    BigDecimal a = ArithmeticUtil.sub(wa.getBalance().toString(), money);
                    wa.setBalance(a);
                    wa.setUpdateTime(new Date());
                    int result = usersWalletMapper.updateByPrimaryKeySelective(wa);
                    if (result > 0) {
                        //添加账单信息
                        billService.addBill(r.getOutBizNo(), userId, "提现到支付宝", Comments.SERZERBAL_PUT, money, Const.CASH_WITHDRAWAL_ICONS);
                    }
                } else {
                    return Result.fail(r.getCode());
                }
            } else {
                return Result.publicResult(401, "请绑定支付宝");
            }
        }
        return Result.success();
    }
}
